In this blog, I’m explaining the concept of namespace and class and difference between them.
Class
In the object oriented programming, class is the collection data and methods. Class is like a blueprint. It defines data and behavior of a type. In C# class contains constructor, variables, methods, and more. Here are a following suitable example:
classSquare// class declaration
{
publicint side = 0; //variable
Square(int n) //Constructor
{
side = n;
}
publicint area() //method
{
return side * side;
}
}
In this example, a class of square which have variable, constructor and method.
Namespace
Namespace is the collection of class, interface, struct, enum and delegate. Namespace is the facility that helps us find and understand how a code base is arranged. A namespace is designed for providing a way to keep one set of name to another. Within a namespace we can declare another namespace. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries.
The built-in libraries are organized within namespace. Take the String class. It is available within the System namespace. To call the static String.Equals() method of the String class, we use its fully qualified name. Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined.
using System;
namespace NamespaceExample
{
classTest
{
publicbool checkString(String str1, String str2)
{
returnString.Equals(str1, str2);
}
}
}
In this example, built in System namespace String class Equals method be used.
Here given a suitable example for namespace:
Here we create namespace;
namespace Calculator
{
classMathCalculator
{
publicint sum(int a, int b)
{
return a + b;
}
publicint sub(int a, int b)
{
return a - b;
}
publicint mul(int a, int b)
{
return a * b;
}
publicint div(int a, int b)
{
return a - b;
}
}
namespace NestedNameSpaceSquare
{
classSquare
{
publicint side=0;
publicvoid getSide(int n)
{
side = n;
}
publicint area()
{
return side * side;
}
}
}
}
In this example, I’m creating a name of calculation and nested namespace also in this example.
Here we use the namespace in own program:
using System;
using Calculator;
using Calculator.NestedNameSpaceSquare;
namespace NameSpaceExample
{
classTest
{
staticvoid Main(string[] args)
{
MathCalculator mthCalObj = newMathCalculator();
Console.WriteLine("Addition of two numbers : " + mthCalObj.sum(10, 20));
Square squareObj = newSquare();
squareObj.getSide(5);
Console.WriteLine("Square of Area is : " + squareObj.area());
Console.ReadKey();
}
}
}
Output is:
Addition of two numbers: 30 Square of Area is: 25 In this example, I’m using namespace Calculator and also import NestedNameSpaceSquare.
Note:
Namespace is like a house and class is like room. The big difference is namespace is the collection of class’s, enum, struct and delegate but class is the part of the namespace.
Leave Comment